################################## 
############ Preamble ############ 
################################## 

# set language to English
Sys.setenv(LANG = "en")

# clean up
rm(list = ls())

# Set working directory: please set your own
#setwd("~/Dropbox/JOP third submission/JOP replication/")

# Load necessary packages
library(tidyverse)
library(haven)
library(psych)


# Import dataset
data <- read.dta13("01_data/elections_ciutadella.dta")

# Subset 2019 election
election_2019 <- data %>%
  filter(year == 2019) %>%
  mutate(election_type = as.numeric(election_type))

# Get descriptives
means <- describeBy(election_2019$pp_voteshare, 
                    group = election_2019$election_type, mat = T)

# Set a seed because of the jittering
set.seed(2408)

# Plot
pp_2019_plot <- means %>%
  mutate(ci_upper = mean + 1.96 * se) %>%
  mutate(ci_lower = mean - 1.96 * se) %>%
  mutate(election_type = as.double(group1)) %>%
  right_join(election_2019, by = "election_type") %>%
  ggplot(aes(x = election_type_string, y = pp_voteshare, color = as.factor(treatment))) +
  scale_color_manual(values = c("black", "red")) +
  theme_bw() +
  geom_point(alpha = 0.1, position = position_jitter(width = 0.1)) +
  geom_point(aes(x = election_type_string, y = mean)) +
  labs(x = "Election type", y = "Vote share for PP") +
  scale_y_continuous(limits = c(0, 31)) +
  geom_errorbar(aes(ymin = ci_lower, ymax = ci_upper), width = .05,
                position = position_dodge(.9)) +
  theme(legend.position = "none")
pp_2019_plot

ggsave("04_plots/figured3.png", plot = pp_2019_plot, width = 12, height = 10, units = "cm")